Page({
  data: {
    categories: [],
    currentCategory: null,
    currentQuestion: null,
    timer: null,
    timeLeft: 0,
    isRecording: false,
    result: null,
    showResult: false,
    isRecording: false,
    tempFilePath: '/temp',
    savedFilePath: '/temp'
  },

  onLoad: function() {
    // 从全局数据获取分类
    const app = getApp();
    this.setData({
      categories: app.globalData.categories
    });
  },

  // 开始随机问题面试
  startRandomInterview: function() {
    const app = getApp();
    const allQuestions = [];

    // 收集所有分类的问题
    app.globalData.categories.forEach(category => {
      if (category.questions && category.questions.length) {
        category.questions.forEach(question => {
          allQuestions.push(Object.assign({}, question, {
              category: category
            }));
        });
      }
    });

    if (allQuestions.length === 0) {
      wx.showToast({
        title: '没有可用的面试问题',
        icon: 'none'
      });
      return;
    }

    // 随机选择一个问题
    const randomIndex = Math.floor(Math.random() * allQuestions.length);
    const selected = allQuestions[randomIndex];

    this.setData({
      currentCategory: selected.category,
      currentQuestion: selected,
      timeLeft: 60,
      showResult: false
    });

    this.startTimer();
  },

  // 开始指定分类面试
  startInterview: function(e) {
    const categoryId = e.currentTarget.dataset.id;
    const app = getApp();
    const category = app.globalData.categories.find(c => c.id === categoryId);
    
    if (category) {
      // 随机选择一个问题
      const randomIndex = Math.floor(Math.random() * category.questions.length);
      const question = category.questions[randomIndex];
      
      this.setData({
        currentCategory: category,
        currentQuestion: question,
        timeLeft: 60, // 60秒回答时间
        showResult: false
      });
      
      // 开始倒计时
      this.startTimer();
    }
  },

  // 开始倒计时
  startTimer: function() {
    const timer = setInterval(() => {
      this.setData({
        timeLeft: this.data.timeLeft - 1
      });
      
      if (this.data.timeLeft <= 0) {
        clearInterval(timer);
        this.setData({
          timer: null
        });
        
        // 时间到，自动生成结果
        if (!this.data.isRecording) {
          this.generateResult();
        }
      }
    }, 1000);
    
    this.setData({
      timer: timer
    });
  },

  // 开始/停止录音
  toggleRecording: function() {
    if (this.data.isRecording) {
      // 停止录音
      this.setData({
        isRecording: false
      });

      this.stopRecording() 
      console.log("保存录音文件");
      this.saveRecording()


      
      // 生成结果
      this.generateResult();
      
      // 停止倒计时
      if (this.data.timer) {
        clearInterval(this.data.timer);
        this.setData({
          timer: null
        });
      }
    } else {
      // 开始录音
      this.setData({
        isRecording: true
      });

      //开始录音
     this.startRecording()
      
      // 模拟录音
      console.log('开始录音...');
    }
  },

    // 检查权限
    checkMicrophonePermission() {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userMicrophone']) {
            wx.authorize({
              scope: 'scope.userMicrophone',
              fail: () => {
                wx.showModal({
                  title: '提示',
                  content: '请授权麦克风权限以使用录音功能',
                  showCancel: false
                });
              }
            });
          }
        }
      });
    },
  
    // 开始录音
    startRecording() {
      this.recorderManager = wx.getRecorderManager();
      this.recorderManager.start({
        duration: 60000,
        format: 'mp3',
        success: (res) => {
          console.log(res);

          this.setData({ tempFilePath: res.tempFilePath });
        }
      });
      
      this.recorderManager.onStop((res) => {
        console.log(res.tempFilePath);
        this.setData({ 
          isRecording: false,
          tempFilePath: res.tempFilePath 
        });

        // 尝试播放音频（验证文件是否可用）
      const audioContext = wx.createInnerAudioContext();
      audioContext.src = res.tempFilePath;
      audioContext.play();
      });
      
      this.setData({ isRecording: true });
    },
  
    // 停止录音
    stopRecording() {
      if (this.recorderManager) {
        this.recorderManager.stop();
        this.setData({ isRecording: false });
      }
    },
  
    // 保存录音
    saveRecording() {
      if (this.data.tempFilePath) {
        wx.saveFile({
          tempFilePath: this.data.tempFilePath,
          success: (res) => {
            console.log("保存录音文件");
            console.log(res.savedFilePath+"====");
            this.setData({ savedFilePath: res.savedFilePath });
            wx.showToast({ title: '保存成功' });
          }
        });
      }
    },
  
    // 播放录音
    playRecording() {
      const filePath = this.data.savedFilePath || this.data.tempFilePath;
      if (!filePath) return;
      
      this.audioContext = wx.createAudioContext();
      this.audioContext.src = filePath;
      this.audioContext.play();
    },
  
    // 停止播放
    stopPlaying() {
      if (this.audioContext) {
        this.audioContext.pause();
      }
    },


  // 生成面试结果
  generateResult: function() {
    // 模拟AI分析，生成结果
    const score = Math.floor(Math.random() * 40) + 60; // 60-100分
    const feedback = this.generateFeedback(score);
    
    const result = {
      score: score,
      feedback: feedback,
      strengths: this.generateStrengths(score),
      improvements: this.generateImprovements(score),
      category: this.data.currentCategory.name,
      question: this.data.currentQuestion.question,
      timestamp: new Date().toISOString()
    };
    
    // 保存面试记录
    const app = getApp();
    app.addInterviewRecord(result);
    
    this.setData({
      result: result,
      showResult: true
    });
  },

  // 生成反馈
  generateFeedback: function(score) {
    if (score >= 90) {
      return "你的回答非常出色！逻辑清晰，内容完整，表达流畅，展现了很强的专业能力和沟通技巧。";
    } else if (score >= 80) {
      return "你的回答很好！有清晰的思路和充分的细节，表达也比较流畅。继续保持！";
    } else if (score >= 70) {
      return "你的回答不错，但还有一些可以改进的地方。可以更加结构化地组织思路，提供更多具体例子。";
    } else {
      return "你的回答需要一些改进。建议在回答前先理清思路，突出重点，并提供具体的案例支持。";
    }
  },

  // 生成优点
  generateStrengths: function(score) {
    const strengths = [
      "逻辑清晰",
      "表达流畅",
      "内容完整",
      "例子丰富",
      "专业知识扎实",
      "沟通技巧良好",
      "思路开阔"
    ];
    
    const selected = [];
    const count = Math.floor(score / 20) + 1;
    
    while (selected.length < count) {
      const randomIndex = Math.floor(Math.random() * strengths.length);
      if (!selected.includes(strengths[randomIndex])) {
        selected.push(strengths[randomIndex]);
      }
    }
    
    return selected;
  },

  // 生成改进点
  generateImprovements: function(score) {
    const improvements = [
      "增加具体例子",
      "提高表达清晰度",
      "加强逻辑结构",
      "增加专业深度",
      "提高回答速度",
      "增加眼神交流",
      "减少口头禅"
    ];
    
    const selected = [];
    const count = Math.floor((100 - score) / 20) + 1;
    
    while (selected.length < count) {
      const randomIndex = Math.floor(Math.random() * improvements.length);
      if (!selected.includes(improvements[randomIndex])) {
        selected.push(improvements[randomIndex]);
      }
    }
    
    return selected;
  },

  // 查看详细报告
  viewReport: function() {
    wx.navigateTo({
      url: `/pages/report/report?timestamp=${this.data.result.timestamp}`
    });
  },

  // 查看所有面试分类
  viewAllCategories: function() {
    wx.switchTab({
      url: '/pages/category/category'
    });
  },

  // 查看面试历史
  viewHistory: function() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  onUnload: function() {
    // 页面卸载时清除定时器
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },
  closeInterview:function(){
      this.setData({
        currentQuestion:""
      })
  }
});
